<?php

require_once dirname(__FILE__) . '/sdk/facebook/facebook.php';

class facebook_api implements interface_platform {

	private $fbObj;
	private $sitemid;
	private $session;
	private $friends;
	private $me;

	function getUserPlatformId() {
		return $this->sitemid;
	}

	function init($type) {

		if(!defined('FACEBOOK_APPID')) die('unset FACEBOOK_APPID');
		if(!defined('FACEBOOK_SECRET')) die('unset FACEBOOK_SECRET');

		$this->fbObj = new Facebook(array(
			'appId'  => FACEBOOK_APPID,
			'secret' => FACEBOOK_SECRET,
			'cookie' => true,
			'domain' => ''
		));

		//
		$this->sitemid = $this->fbObj->getUser();
		if(!is_null($this->sitemid)) {
			$this->session = $this->fbObj->getSession();
		} else {
			$str = http_build_query($_REQUEST);
			$login_url = $this->fbObj->getLoginUrl(array(
				'req_perms' => 'email,publish_stream',
				'next' => 'http://apps.facebook.com/' . GAME_IN_FACEBOOK . '/?' . $str,
				'cancel_url' => 'http://apps.facebook.com/' . GAME_IN_FACEBOOK . '/?cmd=canceled&' . $str,
			));

echo <<<EOT
<script>top.location.replace("$login_url");</script>
正在引導您進入Facebook授權頁面, 請稍候...
EOT;
exit;
		}
	}

	function init_inopt() {

	}

	function isNeedUpdate($uid) {
		return false;

		$x = mdl_account::getInstance()->getAccountOpt($uid);
		if(isset($x['is_needupdate']) && $x['is_needupdate'] == '1') {
			return true;
		}

		return false;
	}

	function getUserInfo($type) {

		try {
			$this->me = $this->fbObj->api('/me?fields=id,name,first_name,gender,friends'); // ,friends
		} catch (FacebookApiException $ex) {
echo <<<EOT
<script>top.location.replace('http://apps.facebook.com/mahjongtw/');</script>
EOT;
exit;
			exit;
		}

		if(empty($this->me) || !isset($this->me['id'])) return array();

		switch($this->me['gender']) {
		case 'male': case '男性': case '男': case 'laki-laki': case 'lelaki': case 'erkek': case 'homme':
			$sex = 0;
			break;
		case 'female': case '女性': case '女': case 'perempuan': case 'nữ': case 'หญิง':
			$sex = 1;
			break;
		default:
			$sex = 2;
		}
		return new mdl_object_remoteuserinfo($this->me['id'], $this->me['name'], $this->me['first_name'], '', $sex);
	}

	function getUserContact() {
		return new mdl_object_remoteusercontact();
	}

	function getSession() {
		return $this->session;
	}

	function getGameUrl() {
		return urlencode('');
	}
}

return new facebook_api();